<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--      筛选-->
      <!--      分栏24占满 -->
      <el-col :span="24" :xs="24">
        <el-form v-if="!loading" label-position="top" :rules="rules" :model="problemData" ref="problemForm" size="small"  label-width="100px">

          <el-row :gutter="20" :span="24">
            <el-col :span="4">
              <el-form-item label="编码前缀" prop="problemIdPrefix">
                <el-input v-model="problemData.problemIdPrefix"  placeholder="输入前缀" >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="编码" prop="problemId">
                <el-input  placeholder="请输入编码"
                           clearable
                           v-model="problemData.problemId"
                           class="input-with-select">
                </el-input>
              </el-form-item>
            </el-col >
          </el-row>

          <el-form-item label="标题" prop="title">
            <el-input
              v-model="problemData.title"
              placeholder="请输入标题"
              clearable
            />
          </el-form-item>
          <el-form-item label="来源" prop="source">
            <el-input
              v-model="problemData.source"
              placeholder="请输人来源"
              clearable
            />
          </el-form-item>
          <el-row :gutter="20" :span="24">
            <el-col :span="8">
              <el-form-item label="时间限制（ms)" prop="timeLimit">
                <el-input
                  type="number"
                  v-model="problemData.timeLimit"
                  placeholder="请输入时间限制"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="内存限制（kb）" prop="memoryLimit">
                <el-input
                  type="number"
                  v-model="problemData.memoryLimit"
                  placeholder="请输入内存限制"
                  clearable
                />
              </el-form-item>
            </el-col >
            <el-col :span="8">
              <el-form-item label="栈限制（kb）" prop="stackLimit">
                <el-input
                  type="number"
                  v-model="problemData.stackLimit"
                  placeholder="请输入栈限制"
                  clearable
                />
              </el-form-item>
            </el-col >
          </el-row>
          <el-form-item label="描述" prop="description">
            <md-editor ref="descriptionMd" :default-data="problemData.description"/>
          </el-form-item>
          <el-form-item label="输入描述" prop="input">
            <md-editor ref="inputMd" :default-data="problemData.input"/>
          </el-form-item>
          <el-form-item label="输出描述" prop="output">
            <md-editor ref="outputMd" :default-data="problemData.output"/>
          </el-form-item>
          <el-form-item label="提示" prop="prompt">
            <md-editor ref="promptMd" :default-data="problemData.prompt"/>
          </el-form-item>
          <el-form-item label="题面样例" prop="exampleList">
            <el-collapse v-show="exampleList.length">
              <el-collapse-item :key="index" v-for="(item,index) in exampleList">
                <template slot="title">
                  <span >样例 {{index+1}}</span>
                </template>
                <el-row  :span="24" :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="输入">
                      <el-input
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 4}"
                        placeholder="请输入内容"
                        v-model="item.input"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="输出">
                      <el-input
                        label="输出"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 4}"
                        placeholder="请输入内容"
                        v-model="item.output"/>
                    </el-form-item>
                  </el-col>

                  <el-col  :offset="12" :span="12">
                    <el-button @click="addExample(index,0,exampleList)" type="info">上面插入</el-button>
                    <el-button @click="addExample(index,1,exampleList)"  type="info">下面插入</el-button>
                    <el-button @click="removeExample(index,exampleList)" type="danger">删除</el-button>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
            <el-button @click="addExample(exampleList.length,0,exampleList)" style="width: 100%">新增一个样例</el-button>
          </el-form-item>

          <el-form-item label="标签" prop="tagIds">
            <el-select
              style="width: 100%"
              v-model="problemData.tagIds"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="输入标签名称"
              :remote-method="remoteGetTagList"
              :loading="tagLoading">
              <el-option
                v-for="item in tagList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-row :gutter="20" :span="24">
            <el-col :span="12">
              <el-form-item label="权限" prop="auth">
                <el-select
                  v-model="problemData.auth"
                  placeholder="选择权限"
                >
                  <el-option
                    v-for="dict in authList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类型" prop="type">
                <el-select
                  v-model="problemData.type"
                  placeholder="选择类型"
                >
                  <el-option
                    v-for="dict in typeList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col >
          </el-row>
          <el-row :gutter="20" :span="24">
            <el-col :span="12">
              <el-form-item label="难度" prop="difficultyId">
                <!--                <reference :component="() => import('@/views/problemType/index')"-->
                <!--                           title="题库参照"-->
                <!--                           :data="{-->
                <!--                  value:problemData.difficultyId,-->
                <!--                  name:'主题库'-->
                <!--                }">-->
                <!--                </reference>-->
                <el-select
                  style="width: 100%"
                  v-model="problemData.difficultyId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="输入难度名称"
                  :remote-method="remoteGetDifficulty"
                  :loading="difficultyLoading">
                  <el-option
                    v-for="item in difficultyList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col >
            <el-col :span="12">
              <el-form-item label="题库" prop="problemTypeId">
                <el-select
                  style="width: 100%"
                  v-model="problemData.problemTypeId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="输入题库名称"
                  :remote-method="remoteGetProblemType"
                  :loading="problemTypeLoading">
                  <el-option
                    v-for="item in problemTypeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col >
          </el-row>
          <el-form-item label="判题模式" prop="judgeMode">
            <template>
              <el-radio v-model="problemData.judgeMode" label="default">普通判题</el-radio>
<!--              <el-radio v-model="problemData.judgeMode" :label=2>特殊判题</el-radio>-->
<!--              <el-radio v-model="problemData.judgeMode" :label=3>交互判题</el-radio>-->
            </template>
          </el-form-item>
          <el-form-item label="代码模板" prop="problemCase">
            <el-select
              style="width: 100%"
              v-model="languageIdList"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="输入语言名称"
              :remote-method="remoteGetLanguages"
              @change="changeLanguage"
              @remove-tag="removeLanguage"
              :loading="languagesLoading">
              <el-option
                v-for="item in languageList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-collapse v-show="problemData.problemLanguageList && problemData.problemLanguageList.length" accordion>
                <el-collapse-item :key="item.id" v-for="(item,index) in problemData.problemLanguageList">
                  <template slot="title">
                    <span>{{item.name}}</span>
                  </template>
                    <el-input
                      type="textarea"
                      :autosize="{ minRows: 4}"
                      placeholder="预制模板"
                      v-model="item.code"/>
                </el-collapse-item>
              </el-collapse>
          </el-form-item>
          <el-form-item label="评测数据" prop="judgeCaseMode">
            <template>
              <el-radio v-model="problemData.testCaseSource" :label=0>数据库</el-radio>
              <el-radio v-model="problemData.testCaseSource" :label=1>文件夹</el-radio>
            </template>
            <el-upload
              style="margin: 20px 0"
              action=""
              :before-upload="beforeUpload"
              :httpRequest="httpRequest">
              <el-button size="small" type="primary">解析文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传zip文件，且不超过2MB。题目测试用例的文件名分别为*.in, *.out，或者*input*.txt, *output*.txt ，其他形式的文件后台均不识别</div>
            </el-upload>
            <el-collapse v-show="problemData.problemCase && problemData.problemCase.length" >
              <el-collapse-item :key="index" v-for="(item,index) in problemData.problemCase">
                <template slot="title">
                  <span>样例 {{index+1}}</span>
                </template>
                <el-row :span="24" :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="输入">
                      <el-input
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 4}"
                        placeholder="请输入内容"
                        v-model="item.input"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="输出">
                      <el-input
                        label="输出"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 4}"
                        placeholder="请输入内容"
                        v-model="item.output"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-input
                      v-model="item.score"
                      placeholder="请输入分数"
                      clearable
                    >
                      <i
                        class="el-icon-edit el-input__icon"
                        slot="suffix"
                      >
                      </i>
                    </el-input>
                  </el-col>
                  <el-col :span="12">
                    <el-button @click="addExample(index,0,problemData.problemCase)" type="info">上面插入</el-button>
                    <el-button @click="addExample(index,1,problemData.problemCase)"  type="info">下面插入</el-button>
                    <el-button @click="removeExample(index,problemData.problemCase)" type="danger">删除</el-button>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
            <el-button @click="addExample(problemData.problemCase.length,0,problemData.problemCase)" style="width: 100%">新增一个样例</el-button>
         </el-form-item>
          <el-form-item label="是否可分享" prop="codeShare">
            <el-switch
              v-model="problemData.codeShare"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
          <el-form-item label="自动去除代码每行末尾空白符" prop="isRemoveEndBlank">
            <el-switch
              v-model="problemData.isRemoveEndBlank"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
          <el-form-item label="公开评测点数据结果" prop="openCaseResult">
            <el-switch
              v-model="problemData.openCaseResult"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="24">
        <el-button :loading="savaLoading" type="sussess" @click="saveProblem" style="width: 100%">保存题目</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import MdEditor from '@/components/mdEditor'
import Reference from '@/components/Reference'
import ProblemType from '@/views/problemType'
import Problem from '@/views/problem'
import * as tagApi from "@/api/tag.js"
import * as languagesApi from "@/api/languages"
import * as problemApi from "@/api/problem"
import * as problemTypeApi from "@/api/problemType"
import * as difficultyApi from '@/api/difficulty'
import { examplesToString ,stringToExamples } from '@/utils/problem'
import { query } from '@/api/languages'
import { getUploadToken } from '@/api/system/common'
import * as qiniu from 'qiniu-js'
import { uploadTestcaseZip } from '@/api/problem'
export default {
  name: 'addProblem',
  components: { Problem, ProblemType, Reference, MdEditor },
  data(){
    return{
      loading:false,
      tagLoading:false,
      languagesLoading:false,
      difficultyLoading:false,
      problemTypeLoading:false,
      savaLoading:false,
      problemData : {
        problemIdPrefix:'',
        problemId:undefined,
        title:undefined,
        input:undefined,
        description:undefined,
        output:undefined,
        prompt:undefined,
        examples:undefined,
        tagIds:[],
        problemLanguageList:[],
        problemCase:[],
        timeLimit:1000,
        memoryLimit:262144,
        stackLimit:262144,
        auth:0,
        type:1,
        source:undefined,
        difficultyId:"163",
        problemTypeId:"1749993556463947777",
        codeShare:1,
        judgeMode:"default",
        judgeCaseMode:"default",
        testCaseSource:0,
        isRemoveEndBlank:1,
        openCaseResult:1
      },
      exampleList:[

      ],
      authList:[
        {
          value:0,
          label:"公开"
        },
        {
          value:1,
          label:"私有"
        },
        {
          value:2,
          label:"比赛"
        }
      ],
      typeList:[
        {
          label:"ACM",
          value:0,
        },
        {
          label:"OI",
          value:1,
        },
      ],
      tagList:[],
      difficultyList:[],
      languageList:[],
      problemTypeList:[],
      languageIdList:[],
      rules: {
        // problemId: {
        //   required: true,
        //   message: "问题编号不能为空",
        //   trigger: "blur",
        // },
        title: {
          required: true,
          message: "标题不能不为空",
          trigger: "blur",
        },
        // input: {
        //   required: true,
        //   message: "输入不能为空",
        //   trigger: "blur",
        // },
        // output: {
        //   required: true,
        //   message: "输出不能为空",
        //   trigger: "blur",
        // },
        difficultyId: {
          required: true,
          message: "难度不能为空",
          trigger: "blur",
        },
        problemTypeId: {
          required: true,
          message: "题库不能为空",
          trigger: "blur",
        },
        timeLimit: {
          required: true,
          message: "时间限制不能为空",
          trigger: "blur",
        },
        memoryLimit: {
          required: true,
          message: "内存限制不能为空",
          trigger: "blur",
        },
        stackLimit: {
          required: true,
          message: "栈内存限制不能为空",
          trigger: "blur",
        },
        judgeCaseMode: {
          required: true,
          message: "评测数据不能为空",
          trigger: "blur",
        },
      },
    }
  },
  created() {
    const id = this.$route.query.id;
    //console.log(id)
    if(id!=undefined && id!=null){
      this.loading = true;
      problemApi.query(id).then(res => {
        console.log(res)
        this.problemData = res.data
        this.tagList = res.data.tagList || []
        if(this.tagList.length == 0)
          this.remoteGetTagList()
        this.exampleList = stringToExamples(res.data.examples) || []
        if(this.exampleList == null || this.exampleList == undefined)
          this.exampleList = []

        this.languageList = res.data.languageList || []
        if(this.languageList == null || this.languageList == undefined)
          this.languageList = []
        this.problemData.problemLanguageList = this.problemData.problemLanguageList || []
        //languageIdList
        if(this.languageList.length == 0)
          this.remoteGetLanguages();
        else {
          this.languageIdList = this.languageList.map(item => item.id);
        }
        if(res.data.problemType)
          this.problemTypeList.push(res.data.problemType)
        else
          this.remoteGetProblemType();
        if(res.data.difficulty)
          this.difficultyList.push(res.data.difficulty)
        else
          this.remoteGetDifficulty();
      }).finally(() => {
        this.loading = false;
      })
    }else{
      this.remoteGetTagList();
      this.remoteGetLanguages();
      this.remoteGetDifficulty();
      this.remoteGetProblemType();
    }
  },
  methods:{
    remoteGetTagList(query){
      this.tagLoading = true;
      tagApi.list({ name: query }).then(res => {
        this.tagList = res.data.rows;
        this.tagLoading = false;
      })
    },
    remoteGetLanguages(query){
      this.languagesLoading = true;
      languagesApi.list({ name: query }).then(res => {
        this.languageList = res.data.rows;
        this.languagesLoading = false;
      })

    },
    remoteGetDifficulty(query){
      this.difficultyLoading = true;

      difficultyApi.list({ name: query }).then(res => {
        this.difficultyList = res.data.rows;
        this.difficultyLoading = false;
      })
    },
    remoteGetProblemType(query){
      this.problemTypeLoading = true;
      problemTypeApi.list({ name: query }).then(res => {
        this.problemTypeList = res.data.rows;
        this.problemTypeLoading = false;
      })
    },
    addExample(index,type,obj){
      const item = {
        input:index + 1,
        output:index +1,
        score : 10,
      }
      if(type == 0){
        obj.splice(index, 0, item); // 在指定下标的第一个位置插入数据
      }else if(type == 1){
        obj.splice(index+1, 0, item); // 在指定下标的第一个位置插入数据
      }
    },
    removeExample(index,obj){
      obj.splice(index, 1);
    },
    removeLanguage(e){

    },
    saveProblem(){
      this.problemData.input = this.$refs.inputMd.getValue();
      this.problemData.output = this.$refs.outputMd.getValue();
      this.problemData.prompt = this.$refs.promptMd.getValue();
      this.problemData.description = this.$refs.descriptionMd.getValue();
      this.problemData.examples = examplesToString(this.exampleList);
     // console.log(this.problemData)
      this.$refs["problemForm"].validate(valid => {
        if (valid) {
          this.savaLoading = true;
          problemApi.saveOrUpdate(this.problemData).then(res => {
            this.$message.success("保存成功！")
          }).catch(err => {

          }).finally(() => {
            this.savaLoading = false;
          })
        }else{
          this.$message.error("校验失败！")
        }
      });
    },
    changeLanguage(e){
      this.problemData.problemLanguageList = this.problemData.problemLanguageList.filter(item => e.includes(item.lid));
      e.forEach(item => {
        if (!this.problemData.problemLanguageList.map(t => t.lid).includes(item)) {
          let t = this.languageList.filter(t => t.id == item);
          if(t.length)
            this.problemData.problemLanguageList.push({
              lid:t[0].id,
              code:t[0].codeTemplate,
              name:t[0].name
            });

        }
      });
    },
    beforeUpload(file){
     // console.log(file.type)
      const isJPG = file.type === 'application/x-zip-compressed';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传的内容只能是 ZIP 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传内容不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    //上传
    async httpRequest({ file }){
      console.log(file)
      // 创建一个 FormData 对象，用于构建请求参数
      const formData = new FormData();
      formData.append('file', file); // 将文件添加到 FormData 中

      problemApi.uploadProblemCaseZip(formData).then(res=>{
        this.problemData.problemCase.push(...res.data)
      })

      //阻止默认上传行为
      return false;
    },

  }
}
</script>

<style scoped>

</style>
